package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.AddressDao;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageParam;
import com.itheima.entity.Result;
import com.itheima.pojo.*;
import com.itheima.utils.DateUtils;
import org.apache.zookeeper.data.Id;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import sun.security.util.Length;

import java.util.ArrayList;
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
import java.security.PublicKey;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 体检预约服务
 */
@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Autowired
    private MemberDao memberDao;

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private AddressDao addressDao;

    //体检预约
    public Result order(Map map) throws Exception {

        //1.检查当前日期是否进行了预约设置
        String orderDate = (String) map.get("orderDate");
        Date date = DateUtils.parseString2Date(orderDate);



        /*
                 新增时间判断
        */
        Date nowDate = new Date();
        if (date!=null){
            if (date.getTime()<nowDate.getTime()){
                return new Result(false,"预约日期不能低于当前日期！");
            }
        }



        OrderSetting orderSetting = orderSettingDao.findByOrderDate(date);
        if(orderSetting == null){
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        //2.检查预约日期是否预约已满
        int number = orderSetting.getNumber();//可预约人数
        int reservations = orderSetting.getReservations();//已预约人数
        if(reservations >= number){
            //预约已满，不能预约
            return new Result(false,MessageConstant.ORDER_FULL);
        }

        //检查当前用户是否为会员，根据手机号判断
        String telephone = (String) map.get("telephone");
        Member member = memberDao.findByTelephone(telephone);

        //3.防止重复预约
        if(member != null){
            Integer memberId = member.getId();
            int setmealId = Integer.parseInt((String)map.get("setmealId"));
            Order order = new Order(memberId, date, null, null, setmealId);
            List<Order> list = orderDao.findByCondition(order);
            if(list != null && list.size() > 0){
                //已经完成了预约，不能重复预约
                return new Result(false,MessageConstant.HAS_ORDERED);
            }
        }
        //可以预约，设置预约人数加一
        orderSetting.setReservations(orderSetting.getReservations()+1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);

        // 4.检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
        if(member == null){
            //当前用户不是会员，需要添加到会员表
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            memberDao.add(member);
        }

        //5.保存预约信息到预约表
        Order order = new Order(member.getId(), date, (String)map.get("orderType"), Order.ORDERSTATUS_NO,
                Integer.parseInt((String)map.get("setmealId")));
        orderDao.add(order);


        String organizationAddress = (String) map.get("organizationAddress");
        if (organizationAddress != null) {
            Integer id = addressDao.findAddressId(organizationAddress);
            addressDao.addOrder(id, order.getId());
        }

        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());

    }

    //根据id查询预约信息，包括体检人信息、套餐信息
    public Map findById(Integer id) throws Exception {
        Map map = orderDao.findById4Detail(id);
        if(map != null){
            //处理日期格式
            Date orderDate = (Date) map.get("orderDate");
            map.put("orderDate", DateUtils.parseDate2String(orderDate));
        }
        return map;
    }

    //查询历史预约记录
    public List<Map> findByDate(String telephone , String startDate, String endDate) {
        return orderDao.findByDate(telephone,startDate,endDate);
    }

    //根据id查询预约的详细信息,包括会员信息,预约信息,套餐信息
    public Map findOrderDetailsById(Integer id) throws Exception {
        Map map = orderDao.findById4OrderDetail(id);
        if(map != null){
            //处理日期格式
            Date orderDate = (Date) map.get("orderDate");
            map.put("orderDate", DateUtils.parseDate2String(orderDate));
        }
        return map;
    }

    @Override
    public List<Integer> findOrderCountByday(List<String> list) {
        List<Integer> result = new ArrayList<>();
        for (String day : list) {
            Integer count=orderDao.getOrderCountByDay(day);
            result.add(count);
        }
        return result;
    }

    @Override
    public List<Integer> findvisitCountByday(List<String> list) {
        List<Integer> result = new ArrayList<>();
        for (String day : list) {
            Integer count=orderDao.getVisitCountByDay(day);
            result.add(count);
        }
        return result;
    }

    //根据预约项查询预约信息 及会员姓名
    public OrderMemberSetmealVo findOrderAndMemberById(Integer orderId) {
        return orderDao.findOrderAndMemberById(orderId);
    }


    //修改预约信息 设置关联关系
    public Result edit(OrderMemberSetmealVo oms, Integer setmealId) {

        Integer memberId = oms.getMemberId();
        String memberName = oms.getMemberName();
        Member member = memberDao.findById(memberId);
        if (!member.getName().equals(memberName)){
            //根据预约表外建 修改会员用户姓名
            memberDao.editmemberName(oms.getMemberId(), memberName);
        }
        //查询原表 匹配日期是否改动
        Order order= orderDao.findById(oms.getOrderId());
        Date orderDate = oms.getOrderDate();
        if (orderDate!=order.getOrderDate()){
            //获取预约时间 查询当天是否有预约
            //1.检查当前日期是否进行了预约设置
            OrderSetting orderSetting = orderSettingDao.findByOrderDate(orderDate);
            if (orderSetting == null) {
                return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
            }
            //2.检查预约日期是否预约已满
            int number = orderSetting.getNumber();//可预约人数
            int reservations = orderSetting.getReservations();//已预约人数
            if (reservations >= number) {
                //预约已满，不能预约
                return new Result(false, MessageConstant.ORDER_FULL);
            }
            //可以预约，设置预约人数加一
            orderSetting.setReservations(orderSetting.getReservations() + 1);
            orderSettingDao.editReservationsByOrderDate(orderSetting);
        }

        //修改预约信息列表
        orderDao.edit(oms);
        return new Result(true, MessageConstant.EDIT_ORDER_SUCCESS);
    }

    //删除预约信息
    public void deleteOrder(Integer orderId) {
        orderDao.deleteOrder(orderId);
    }

    //新增预约信息
    public Result addOrder(Map map) throws Exception {


        String phoneNumber = (String) map.get("phoneNumber");
        String name = (String) map.get("memberName");
        map.put("telephone", phoneNumber);
        map.put("orderType", Order.ORDERTYPE_TELEPHONE);
        map.put("orderStatus", Order.ORDERSTATUS_NO);
        map.put("name", name);
        return order(map);
    }

    //按钮修改预约状态
    public void changeStatus(Integer orderId, String orderStatus) {
        orderDao.changeStatus(orderId, orderStatus);
    }


    //分页查询
    @Override
    public PageResult findPage(QueryPageParam param) {
        Integer currentPage = param.getCurrentPage();
        Integer pageSize = param.getPageSize();
        PageHelper.startPage(currentPage, pageSize);
        Page<OrderMemberSetmealVo> page = orderDao.selectByCondition(param);
        return new PageResult(page.getTotal(), page.getResult());
    }
}
